import { defineStore } from 'pinia';
import { ref, computed } from 'vue';
import { PromptElementGroup, UserSettings } from './promps';
import { frameworkGroups } from './defaultGroups';

export const usePromptStore = defineStore('prompt', () => {
  // 状态
  const groups = ref<PromptElementGroup[]>([]);
  const currentGroupId = ref<string>('');
  const userSettings = ref<UserSettings>({
    selectedGroupId: '',
    language: 'cn'
  });
  const elementValues = ref<Record<string, string>>({});

  // 计算属性
  const currentGroup = computed(() => {
    // 确保groups.value是一个数组
    if (!Array.isArray(groups.value)) {
      return null;
    }
    return groups.value.find(group => group.id === userSettings.value.selectedGroupId);
  });

  const generatedPrompt = computed(() => {
    if (!currentGroup.value || !Array.isArray(currentGroup.value.elements)) return '';

    const promptParts: string[] = [];

    currentGroup.value.elements.forEach((element, index) => {
      const value = elementValues.value[element.name_cn] || '';
      if (value.trim()) {
        const title = getElementName(element);
        promptParts.push(`# ${title} \n ${value}`);
      }
    });

    return promptParts.join('\n');
  });

  // 动作
  const setCurrentGroup = (groupId: string) => {
    userSettings.value.selectedGroupId = groupId;
    // 保存到浏览器存储
    browser.storage.sync.set({ selectedGroupId: groupId });
  };

  const setElementValue = (elementName: string, value: string) => {
    elementValues.value[elementName] = value;
  };

  const addGroup = (group: Omit<PromptElementGroup, 'id'>) => {
    const newGroup: PromptElementGroup = {
      ...group,
      id: Date.now().toString()
    };
    groups.value.push(newGroup);
    saveGroupsToStorage();
  };

  const updateGroup = (groupId: string, updates: Partial<PromptElementGroup>) => {
    const index = groups.value.findIndex(group => group.id === groupId);
    if (index !== -1) {
      groups.value[index] = { ...groups.value[index], ...updates };
      saveGroupsToStorage();
    }
  };

  const deleteGroup = (groupId: string) => {
    groups.value = groups.value.filter(group => group.id !== groupId);
    if (currentGroupId.value === groupId) {
      currentGroupId.value = groups.value[0]?.id || '';
    }
    saveGroupsToStorage();
  };

  const setDefaultGroup = (groupId: string) => {
    userSettings.value.selectedGroupId = groupId;
    saveSettingsToStorage();
  };

  const setLanguage = (language: 'cn' | 'en') => {
    userSettings.value.language = language;
    saveSettingsToStorage();
  };

  // 存储相关方法
  const saveGroupsToStorage = async () => {
    await browser.storage.sync.set({ groups: groups.value });
  };

  const saveSettingsToStorage = async () => {
    await browser.storage.sync.set({ userSettings: userSettings.value });
  };

  const loadFromStorage = async () => {
    try {
      console.log('Loading data from storage...');
      const result = await browser.storage.sync.get(['groups', 'userSettings']);

      if (result.groups && Array.isArray(result.groups)) {
        groups.value = result.groups;
      } else {
        groups.value = [...frameworkGroups];
        await saveGroupsToStorage();
      }

      if (result.userSettings) {
        userSettings.value = result.userSettings;
      } else {
        userSettings.value.selectedGroupId = groups.value[0]?.id || '';
        userSettings.value.language = 'cn';
        saveSettingsToStorage();
      }
    } catch (error) {
      console.error('Failed to load data from storage:', error);
      // 出错时初始化为默认值
      groups.value = [...frameworkGroups];
      userSettings.value.selectedGroupId = groups.value[0]?.id || '';
      userSettings.value.language = 'cn';
    }
  };

  const resetAll = async () => {
    await browser.storage.sync.clear();
    await loadFromStorage();
  };
  const importData = async (importGroups: PromptElementGroup[], settings: UserSettings) => {
    // 确保导入的数据是数组
    if (Array.isArray(importGroups)) {
      groups.value = importGroups;
    } else {
      console.error('Imported groups is not an array:', importGroups);
      groups.value = [];
    }
    
    userSettings.value = settings;
    await saveGroupsToStorage();
    await saveSettingsToStorage();
  };

  // 获取元素名称的公共方法
  const getElementName = (element: any) => {
    // 如果当前语言是英文且元素有英文名称，则使用英文名称
    if (userSettings.value.language === 'en' && element.name_en) {
      return element.name_en;
    }
    // 默认使用中文名称，即使当前语言是英文但元素没有英文名称
    return element.name_cn || element.name_en || '';
  };

  // 复制到剪贴板
  const copyToClipboard = async () => {
    try {
      await navigator.clipboard.writeText(generatedPrompt.value);
      return true;
    } catch (error) {
      console.error('Failed to copy to clipboard:', error);
      return false;
    }
  };

  return {
    groups,
    currentGroupId,
    userSettings,
    elementValues,
    currentGroup,
    generatedPrompt,
    setCurrentGroup,
    setElementValue,
    addGroup,
    updateGroup,
    deleteGroup,
    setDefaultGroup,
    setLanguage,
    loadFromStorage,
    importData,
    resetAll,
    getElementName,
    copyToClipboard
  };
});